import torch
# from modelscope import snapshot_download
# from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
# from qwen_vl_utils import process_vision_info
import transformers
import qwen_vl_utils
import os
import base64

from modelscope.models.cv.face_detection.ulfd_slim.vision.ssd.fd_config import image_size

# from test.api_request import image_file
# default: Load the model on the available device(s)
# model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
# "Qwen/Qwen2.5-VL-7B-Instruct", torch_dtype="auto", device_map="auto"
# )
# 模型路径
model_name = ["Qwen/Qwen2.5-VL-32B-Instruct",
              "Qwen/Qwen2.5-VL-7B-Instruct",
              "XiaomiMiMo/MiMo-VL-7B-RL",
              "XiaomiMiMo/MiMo-VL-7B-SFT"
              ]
model_dir = "/home/%s/models/%s" % (os.getlogin(), model_name[1])
model_dtype = torch.bfloat16
model_dev = "auto"
# 量化配置
model_conf = transformers.BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",              # 量化算法：nf4|fp4
    bnb_4bit_compute_dtype=model_dtype,
    bnb_4bit_use_double_quant=True          # 是否启用二次量化
)
# 加载预训练模型
model = transformers.Qwen2_5_VLForConditionalGeneration.from_pretrained(
    model_dir,  # *模型文件的目录
    torch_dtype=model_dtype,        # 模型权重数据类型：float16-FP16-更高精度|bfloat16-BF16-更低精度|float32
    # low_cpu_mem_usage=True        # 是否优化CPU内存
    # load_in_4bit=True,              # 是否4位量化加载
    # load_in_8bit=True,              # 是否8位量化加载
    # quantization_config=model_conf,
    device_map = model_dev          # 模型加载设备：auto|cuda|cpu
)
#
processor = transformers.AutoProcessor.from_pretrained(model_dir, max_pixels=1280 * 28 * 28)

image_file = "/home/%s/data/image/test/pager/test_19.jpg" % os.getlogin()

with open(image_file, 'rb') as f:
    image_base64 = base64.b64encode(f.read()).decode('utf-8')

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image",
                "image": "data:image/jpeg;base64," + image_base64,
            },
            {"type": "text", "text": "获取图片的标题,全部信息输出为json格式"},
        ],
    }
]

# Preparation for inference
text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
image_inputs, video_inputs = qwen_vl_utils.process_vision_info(messages)
inputs = processor(
    text=[text],
    images=image_inputs,
    videos=video_inputs,
    padding=True,
    return_tensors="pt",
)
inputs = inputs.to(model.device)
# inputs = inputs.to("cpu")

# Inference: Generation of the output
generated_ids = model.generate(**inputs, max_new_tokens=128)
generated_ids_trimmed = [out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
output_text = processor.batch_decode(generated_ids_trimmed, skip_special_tokens=True,
                                     clean_up_tokenization_spaces=False)
print(output_text)

'''
文本+base64编码
import base64
from PIL import Image
from io import BytesIO
from transformers import AutoProcessor, AutoModelForCausalLM

# 假设 processor 是你的模型对应的处理器类
processor = AutoProcessor.from_pretrained("model-name")

# 示例输入字典，包含文本和 Base64 编码的图像
input_dict = {
    "text": "这张图片展示了什么？",
    "image": "..."
}

# 解码 Base64 图像
image_data = base64.b64decode(input_dict["image"].split(",")[1])
image = Image.open(BytesIO(image_data))

# 预处理图像
image_inputs = processor(images=image, return_tensors="pt")

# 预处理文本
text_inputs = processor(input_dict["text"], return_tensors="pt")

# 应用聊天模板（假设 apply_chat_template 方法接受文本和图像输入）
# 注意：这里的 apply_chat_template 是假设的方法，具体实现可能不同
formatted_inputs = processor.apply_chat_template(text=text_inputs, images=image_inputs)

# 假设模型是用于生成文本的模型
model = AutoModelForCausalLM.from_pretrained("model-name")

# 生成文本
outputs = model(**formatted_inputs)
'''

'''
import base64
from PIL import Image
from io import BytesIO
from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
from qwen_vl_utils import process_vision_info

# 加载模型和处理器
model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
    "Qwen/Qwen2.5-VL-7B-Instruct-AWQ", torch_dtype="auto", device_map="auto"
)
processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct-AWQ")

# 准备包含Base64编码图片的请求消息
messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image",
                "image": "...",
            },
            {"type": "text", "text": "Describe this image."},
        ],
    }
]

# 准备推理
text = processor.apply_chat_template(
    messages, tokenize=False, add_generation_prompt=True
)
image_inputs, video_inputs = process_vision_info(messages)
inputs = processor(
    text=[text],
    images=image_inputs,
    videos=video_inputs,
    padding=True,
    return_tensors="pt",
)
inputs = inputs.to("cuda")

# 推理：生成输出
generated_ids = model.generate(**inputs, max_new_tokens=128)
generated_ids_trimmed = [
    out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
]
output_text = processor.batch_decode(
    generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
)
print(output_text)
'''
